package com.yycx.module.bus.provider.handler.invoice;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.interceptor.UpdateInterceptor;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.utils.ApiAssert;
import com.yycx.groovy.provider.script.MyGroovyScriptEngine;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.provider.service.BusPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 开票税金更新扩展器
 *
 * @author zyf
 */
@Component("invoicePaymentUpdateHandler2")
public class InvoicePaymentUpdateHandler2 implements UpdateInterceptor<BusPayment> {

    @Autowired
    private MyGroovyScriptEngine groovyScriptEngine;


    @Autowired
    private BusPaymentService paymentService;


    @Override
    public void prepare(CriteriaUpdate criteriaUpdate, EntityMap entityMap, BusPayment payment) {
        Long invoiceUnitId = entityMap.getLong("invoiceUnitId");
        ApiAssert.isNotEmpty("invoiceUnitId不能为空", invoiceUnitId);
        String amountFormulaContent = entityMap.get("amountFormulaContent");
        BigDecimal invoiceAmount = payment.getInvoiceAmount();
        payment.setInvoiceAmount(invoiceAmount);
        BigDecimal taxAmount = calculateTaxAmount(payment, amountFormulaContent);
        payment.setAmount(taxAmount);
        entityMap.put("taxAmount", taxAmount);
        entityMap.put("invoiceAmount", invoiceAmount);
    }

    /**
     * 计算开票税金
     *
     * @param payment
     * @return
     */
    private BigDecimal calculateTaxAmount(BusPayment payment, String amountFormulaContent) {
        BigDecimal taxAmount = new BigDecimal("0");
        ApiAssert.isNotEmpty("税金公式不能为空", amountFormulaContent);
        try {
            Map<String, Object> variable = new HashMap<>();
            variable.put("开票金额", payment.getInvoiceAmount());
            taxAmount = groovyScriptEngine.executeBigDecimal(amountFormulaContent, variable);
        } catch (Exception e) {
            e.printStackTrace();
            ApiAssert.failure("开票税金计算异常");
        }
        return taxAmount;
    }
}
